import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'main_home',
    component: () => import('@/views/MainHome.vue'),
    redirect: () => {
      // 根据不同角色重定向到不同的路由
      const userInfoStr = localStorage.getItem("ts_userInfo");
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        if (userInfo) {
          if (userInfo.usertype === 1 || userInfo.usertype === 0) {
            return '/teacher_home'
          } else if (userInfo.usertype === 2) {
            return '/student_home'
          } else if (userInfo.usertype === 999) {
            return '/admin_home'
          }
        }
        return '/login';
      }
      return '/login';
    },
    children: [
      {
        path: 'teacher_home',
        name: 'teacher_home',
        component: () => import('@/views/TeacherHome.vue')
      },
      {
        path: 'student_home',
        name: 'student_home',
        component: () => import('@/views/StudentHome.vue')
      },
      {
        path: 'admin_home',
        name: 'admin_home',
        component: () => import('@/views/AdminHome.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  }
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
  routes
})
router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    localStorage.setItem("ts_userInfo", "");
    next();
  } else {
    const userInfo = localStorage.getItem("ts_userInfo");
    if (userInfo) {
      next();
    } else {
      next({
        path: "/login",
        query: to.query
      });
    }
  }
})
export default router
